<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        * {
            padding: 0;
            margin: 0;
        }

        .shadow {
            width: 200px;
            height: 200px;
            background-color: rgba(0, 0, 0, 0.4);
            /* margin: 100px; */
            /* transform: translate(); */
            /* position: absolute; */
            position: absolute;
            left: 100px;
            top: 100px;
            user-select: none;
        }

        .sub {
            width: 100px;
            height: 100px;
            background-color: #6ff;
            margin: 50px;
            pointer-events: none;
        }
    </style>
</head>

<body>
    <div class="shadow"></div>
    <div class="shadow"></div>
    <div class="shadow"></div>
    <div class="shadow"></div>
    <div class="shadow"></div>
    <div class="shadow"></div>
</body>
<script>
    function DragEle(ele) {
        this.target = ele;
        this.init();
    }
    DragEle.prototype.init = function () {
        this.randColor();
        this.dargStart();
    }

    DragEle.prototype.dargStart = function () {
        var _this = this;// this 指向dargEle
        this.target.onmousedown = function (e) {
            var e = e || window.event;

            var posX = e.offsetX;
            var posY = e.offsetY;
            // console.log(posX,posY);
            // console.log(this);//  this指向target

            _this.posX = posX;
            _this.posY = posY;
            // console.log(_this);// _this 指向dargEle

            _this.dargMove();
            _this.dargEnd();

        }
    }
    DragEle.prototype.dargMove = function () {
        document.onmousemove = (e) => {
            var e = e || window.event;
            var x = e.pageX - this.posX;
            var y = e.pageY - this.posY;
            // console.log(this);//this 指向dargEle

            this.target.style.left = x + "px";
            this.target.style.top = y + "px";
        }
    }
    DragEle.prototype.dargEnd = function () {
        document.onmouseup = function () {
            document.onmousemove = null;
        }
    }
    DragEle.prototype.randColor = function () {
        var colorStr = "#";
        for (var i = 0; i < 6; i++) {
            var num = Math.round(Math.random() * 15);
            var char = num.toString(16);
            colorStr += char;
        }
        this.target.style.backgroundColor = colorStr;
    }

    var shadowList = document.getElementsByClassName("shadow");

    for (let i = 0; i < shadowList.length; i++) {
        let shadow = shadowList[i];
        var obj =new DragEle(shadow);
    }
</script>

</html>